package handler

import (
	"china-auto-rental/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"path/filepath"
	"strings"
)

func Upload(c *gin.Context) {

	file, err := c.FormFile("image")
	if err != nil {
		return
	}

	etc := strings.ToLower(filepath.Ext(file.Filename))
	if !strings.Contains(".png.jpg", etc) {

		c.JSON(http.StatusOK, &gin.H{
			"code": 100000,
			"msg":  "图片格式只能是png,jpg",
			"data": false,
		})
		return
	}

	if file.Size > 2*1024*1024 {
		c.JSON(http.StatusOK, &gin.H{
			"code": 100000,
			"msg":  "文件大小不得不超过200KB",
			"data": false,
		})
		return

	}

	update, err := pkg.Update(file)
	if err != nil {
		c.JSON(http.StatusOK, &gin.H{
			"code": 100000,
			"msg":  "上传失败",
			"data": nil,
		})
		return
	}

	c.JSON(http.StatusOK, &gin.H{
		"code": http.StatusOK,
		"msg":  "上传成功",
		"data": update,
	})
}
